package cool.mtc.swagger;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * @author 明河
 */
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnProperty(value = "mtc.swagger.ui.enabled", havingValue = "true", matchIfMissing = true)
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SwaggerUiWebFluxConfiguration {
    private final SwaggerProperties swaggerProperties;

    @Bean
    public SwaggerUiWebFluxConfigurer swaggerUiWebFluxConfigurer() {
        return new SwaggerUiWebFluxConfigurer(swaggerProperties.getUi().getBaseUrl());
    }

    @Bean
    public WebFilter swaggerUiWebFilter() {
        return new CustomWebFilter();
    }

    private static class CustomWebFilter implements WebFilter {
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
            String path = exchange.getRequest().getURI().getPath();
            if (path.matches(".*/swagger-ui/")) {
                ServerHttpRequest request = exchange.getRequest()
                        .mutate()
                        .path(StringUtils.trimTrailingCharacter(path, '/') + "/index.html")
                        .build();
                return chain.filter(exchange.mutate().request(request).build());
            }
            return chain.filter(exchange);
        }
    }
}
